package com.appBase.tools;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.appBase.MainActivity;


import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static android.widget.Toast.LENGTH_SHORT;

public class YLHttpClient {

    static YLHttpClient ylHttpClient = null;
    static OkHttpClient okHttpClient = null;

    private static String tokenStr = "";

    public static void setTokenStr(String tokenStr) {
        YLHttpClient.tokenStr = tokenStr;
    }

    public static String getTokenStr() {
        return tokenStr;
    }
    //private Request request;

    public static YLHttpClient getDefaultYLHttpClient() {

        if (ylHttpClient == null) {
            ylHttpClient = new YLHttpClient();
        }
        return ylHttpClient;
    }

    public OkHttpClient okHttpClient(){
        return okHttpClient;
    }

    public YLHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).readTimeout(60,TimeUnit.SECONDS).build();
        }
    }

    public void sendGetRequest(final MainActivity currentActivity, final String url, final Type typeOfData, final HttpCallBack httpCallBack) {
        currentActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //更新UI
                LoadingDialog.getInstance(currentActivity).show();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                YLHttpClient client = YLHttpClient.getDefaultYLHttpClient();
                try {
                    Request request = new Request.Builder().url(url).addHeader("Authorization", tokenStr).build();
                    Response response = okHttpClient.newCall(request).execute();//发送请求
                    responsHandel(currentActivity, response, typeOfData, httpCallBack);
                } catch (IOException e) {
                    e.printStackTrace();
                    currentActivity.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            LoadingDialog.getInstance(currentActivity).dismiss();
                            showMessage(currentActivity, "无法连接到服务器");
//                            currentActivity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    currentActivity.showBaseUrlInput();
//                                }
//                            });

                        }//

                    });
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    currentActivity.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            LoadingDialog.getInstance(currentActivity).dismiss();
                            showMessage(currentActivity, "无法连接到服务器");
//                            currentActivity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    currentActivity.showBaseUrlInput();
//                                }
//                            });
                        }//

                    });
                }
            }
        }).start();
    }

    public void sendPostRequest(final MainActivity currentActivity, final String url, final RequestBody requestBody, final Type typeOfData, final HttpCallBack httpCallBack) {
        currentActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //更新UI
                LoadingDialog.getInstance(currentActivity).show();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                YLHttpClient client = YLHttpClient.getDefaultYLHttpClient();

                try {
                    Request request = new Request.Builder().url(url).post(requestBody).addHeader("Authorization", tokenStr).build();
                    Response response = okHttpClient.newCall(request).execute();//发送请求
                    responsHandel(currentActivity, response, typeOfData, httpCallBack);
                } catch (IOException e) {
                    e.printStackTrace();
                    currentActivity.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            LoadingDialog.getInstance(currentActivity).dismiss();
                            showMessage(currentActivity, "无法连接到服务器");
//                            currentActivity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    currentActivity.showBaseUrlInput();
//                                }
//                            });
                            //httpCallBack.callBack(404, null);
                        }//

                    });
                }
            }
        }).start();
    }

    private void responsHandel(final MainActivity currentActivity, final Response response, final Type typeOfData, final HttpCallBack httpCallBack) throws IOException {

        currentActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //更新UI
                LoadingDialog.getInstance(currentActivity).dismiss();
            }
        });
        if (response.code() != 200) {
            currentActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //更新UI
                    if (response.code() >= 500) {
                        Toast.makeText(currentActivity, "服务器错误" + response.code(), LENGTH_SHORT).show();
                    } else if (response.code() >= 400) {
                        Toast.makeText(currentActivity, "网络请求错误" + response.code(), LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(currentActivity, "错误" + response.code(), LENGTH_SHORT).show();
                    }
                }
            });

        } else {
            String result = null;
            ResponseBody body = response.body();
            result = body.string();
            final String sss = result;

            if (!YLHttpClient.validate(result)) {
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(currentActivity, sss, LENGTH_SHORT).show();
                        if (typeOfData.equals(String.class)) {
                            httpCallBack.callBack(response.code(), sss);
                        }
                    }
                });
                return;
            }
            JsonObject jsonObject = (JsonObject) new JsonParser().parse(result);
            if (jsonObject.get("success").getAsBoolean()) {
                Gson gson = new Gson();
                final Object httpData = (HttpData) gson.fromJson(result, typeOfData);
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //更新UI
                        httpCallBack.callBack(response.code(), httpData);
                    }
                });
            } else {
                final String msg = jsonObject.get("msg").getAsString();
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(currentActivity, msg, LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    private void showMessage(final MainActivity currentActivity, final String message) {

        View decorView = currentActivity.getWindow().getDecorView();
//        SYSTEM_UI_FLAG_FULLSCREEN表示全屏的意思，也就是会将状态栏隐藏
        //设置系统UI元素的可见性
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        uiFlags |= 0x00001000;
        decorView.setSystemUiVisibility(uiFlags);
        AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
        builder.setTitle("提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setTitle("提示");
        builder.setMessage(message);
        builder.show();
    }

    public static boolean validate(String jsonStr) {
        JsonElement jsonElement;
        try {
            jsonElement = new JsonParser().parse(jsonStr);
        } catch (Exception e) {
            return false;
        }
        if (jsonElement == null) {
            return false;
        }
        if (!jsonElement.isJsonObject()) {
            return false;
        }
        return true;
    }


}

